package com.xr.blackhoole.rabbit.template;

import com.xr.blackhoole.mvc.configuration.BlackholeIsolationConfiguration;
import com.xr.blackhoole.mvc.context.BlackholeContext;
import com.xr.blackhoole.mvc.context.BlackholeContextHolder;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;

public class ShadowRabbitTemplate extends RabbitTemplate {

    public ShadowRabbitTemplate(ConnectionFactory connectionFactory) {
        super(connectionFactory);
    }

    @Autowired
    private BlackholeIsolationConfiguration isolationConfiguration;

    @Override
    public void send(final String exchange,
                     final String routingKey,
                     final Message message,
                     @Nullable final CorrelationData correlationData) throws AmqpException {

        BlackholeContext blackholeContext = BlackholeContextHolder.getContext();
        if (blackholeContext == null) {
            super.send(exchange, routingKey, message, correlationData);
        } else {
            message.getMessageProperties().setHeader(BlackholeContextHolder.BLACKHOLE_REQUEST_MARK, blackholeContext.toString());
            String blackholeRoutingKey = isolationConfiguration.generateIsolationKey(routingKey);
            super.send(exchange,blackholeRoutingKey,message,correlationData);
        }

    }
}

